#include "DispatchHandler.h"
#include "GateServer.h"
#include "RPC_account.pb.h"
#include "JME_JsonFile.h"

void DispatchHandler::init()
{
	regMessageHandler(1005, sendMessageToAccount);
}

void DispatchHandler::sendMessageToAccount( JME_TcpSession::JME_TcpSessionPtr session, const JME_MessagePtr& params )
{
 	auto gs = GateServer::getInstance();
 	auto rc = gs->getRpcByName("account");
	if (!rc)
		return;

	string m = params->getMessageStr();

	auto msgJson = JMEngine::file::createWithString(m);
	if (msgJson.isNull())
		return;



	RPC_RequestLogin p;
	p.set_name(msgJson["name"].asString());
	p.set_pwd(msgJson["password"].asString());

	auto cb = [session, params](const JME_Rpc& response)
	{
		RPC_RequestLoginRes p;
		p.ParseFromString(response._params);
		

		Json::Value resJson;
		resJson["state"] = p.res();

		string m = resJson.toSimpleString();
		auto rmsg = JME_Message(1005, m);

		session->writeMessage(rmsg);
	};

	rc->callRpcMethod("requestLogin", &p, cb);
}

